package com.shine.spring.boot.action.websocket.service;

import com.shine.spring.boot.action.websocket.util.ClientInfoProxyGetter;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author: Forward Seen
 * @description: websocket demo
 * @createTime: 2023/9/27 10:54
 * @since: 1.0
 */
@Getter
@Setter
@Slf4j
@ServerEndpoint("/ws")
@Service
public class WebSocketService {

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的WebSocket对象。
     * 虽然@Component默认是单例模式的，但Spring Boot还是会为每个Websocket连接初始化一个bean，所以可以用一个静态set保存起来。
     */
    private static Set<WebSocketService> webSocketSet = new CopyOnWriteArraySet<>();

    /**
     * 以Map的形式存储IP和Session，一个IP可能会有多个Session连接。
     */
    private static Map<String, List<Session>> sessionMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 用于存储一些客户端信息
     */
    private ClientInfoProxyGetter client;

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        this.client = new ClientInfoProxyGetter(session);
        webSocketSet.add(this);
        String clientIp = client.getClientIp();
        log.info("Client IP:{}", client.getClientIp());
        if (sessionMap.containsKey(clientIp)) {
            sessionMap.get(clientIp).add(session);
        } else {
            ArrayList<Session> sessions = new ArrayList<>(1);
            sessions.add(session);
            sessionMap.put(clientIp, sessions);
        }
        log.info("有新连接加入！当前连接数为{}", getConnectionCount());
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        String clientIp = client.getClientIp();
        if (sessionMap.containsKey(clientIp)) {
            List<Session> sessions = sessionMap.get(clientIp);
            sessions.remove(session);
            if (sessions.isEmpty()) {
                sessionMap.remove(clientIp);
            }
        }
        log.info("有连接关闭！当前连接数为{}", getConnectionCount());
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("【来自客户端{}的消息】{}", session.getId(), message);
        publish(message);
    }

    /**
     * 发生错误时调用
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("{}发生错误", session.getId(), error);
    }

    public void send(String message) throws IOException {
        synchronized (session) {
            log.info("Send to {}:{}", session.getId(), message);
            session.getBasicRemote().sendText(message);
        }
    }

    /**
     * 群发消息
     */
    public static void publish(String message) {
        log.info("【websocket广播消息】{}", message);
        for (WebSocketService ws : webSocketSet) {
            try {
                ws.send(message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 获取连接数
     *
     * @return 当前连接数
     */
    public static synchronized int getConnectionCount() {
        return webSocketSet.size();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        WebSocketService that = (WebSocketService) o;
        return session.equals(that.session);
    }

    @Override
    public int hashCode() {
        return Objects.hash(session);
    }
}
